package com.smh.demo1.a17;

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author shiminghui
 * @date 2025/4/21 21:46
 * @description: TODO
 */
public class A17Application {
    public static void main(String[] args) throws Exception {
        AnnotationConfigServletWebServerApplicationContext context =
                new AnnotationConfigServletWebServerApplicationContext(WebConfig.class);
        //System.out.println(context.getEnvironment().getProperty("java.home"));
       /* YamlPropertiesFactoryBean bean = context.getBean(YamlPropertiesFactoryBean.class);
        bean.getObject().forEach((key,value)->{
            System.out.println(key+":"+value);
        });*/

        // 用来解析 @RequestMapping 注解以及其派生注解, DispatcherServlet初始化时创建,并执行解析操作,生成映射关系
        RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);

        // 解析 @RequestMapping 注解, 获取所有映射关系,RequestMappingInfo请求路径,  HandlerMethod处理器方法
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        handlerMethods.forEach((k, v) -> {
            System.out.println(k + ":" + v);
        });
        System.out.println("===========================================================================");

        MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/test5");
//        request.setParameter("id", "1");
//        request.addHeader("token", "123");
        MockHttpServletResponse response = new MockHttpServletResponse();

        // 模拟请求,会根据请求找到对应的处理器方法,还会找到对应的拦截器,返回一个处理器链
        HandlerExecutionChain chain = handlerMapping.getHandler(request);
        System.out.println(chain);

        // 测试处理器适配器调用控制器方法
        MyRequestMappingHandlerAdapter handlerAdapter = context.getBean(MyRequestMappingHandlerAdapter.class);
        handlerAdapter.invokeHandlerMethod(request, response, (HandlerMethod) chain.getHandler());

        // 查看返回值
        byte[] byteArray = response.getContentAsByteArray();
        System.out.println(new String(byteArray, StandardCharsets.UTF_8));

        // 查看handlerAdapter的参数解析器
        System.out.println("参数解析器:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        handlerAdapter.getArgumentResolvers().forEach(System.out::println);
        // 查看handlerAdapter的返回值解析器
        System.out.println("返回值解析器:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        handlerAdapter.getReturnValueHandlers().forEach(System.out::println);

        context.close();
    }
}

